package org.example.day05;

/**
 * 第二章节2.2.16: 锁对象的改变
 *      锁对象的改变，从而导致异步
 */
public class MyThread11 {
    private String lock = "123";
    public void  testMethod(){
        try {
            synchronized (lock){
                System.out.println(Thread.currentThread().getName() + " begin " + System.currentTimeMillis());
//                Thread.sleep(100);
                lock = "456";
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName() + " end " + System.currentTimeMillis());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread11 m11 = new MyThread11();
        Thread11A ta = new Thread11A(m11);
        ta.setName("A");
        Thread11B tb = new Thread11B(m11);
        tb.setName("B");
        ta.start();
//        Thread.sleep(100); //保证A线程先进入方法并修改锁
        tb.start();
    }
}

class Thread11A extends Thread{
    private MyThread11 m11;

    public Thread11A(MyThread11 m11) {
        this.m11 = m11;
    }

    @Override
    public void run() {
        m11.testMethod();
    }
}

class Thread11B extends Thread{
    private MyThread11 m11;

    public Thread11B(MyThread11 m11) {
        this.m11 = m11;
    }

    @Override
    public void run() {
        m11.testMethod();
    }
}
